import ProLayout, { PageContainer, MenuDataItem } from '@ant-design/pro-layout';
import React, { useState, useEffect, useRef } from 'react';
import { Link, history, connect } from 'umi';
import styled from './BasicLayout.less';
import {
  HomeOutlined,
  UnorderedListOutlined,
  SmileOutlined,
  HeartOutlined,
  BorderOuterOutlined,
  BorderInnerOutlined,
  TeamOutlined,
} from '@ant-design/icons';

import GlobalHeader from '../pages/GlobalHeader/index';

import {
  NoticeEmitter,
  ENOAD_ERROR,
  ENOAD_LOGIN_OUT,
} from 'enoad-component-web/dist/src/core/util';
import { doLogin } from '../utils/utils';
import { message } from 'antd';

const IconMap = {
  home: <HomeOutlined />,
  list: <UnorderedListOutlined />,
  smile: <SmileOutlined />,
  heart: <HeartOutlined />,
  custom: <BorderInnerOutlined />,
  all: <BorderOuterOutlined />,
  rbac: <TeamOutlined />,
};

const loopMenuItem = (menus: MenuDataItem[]): MenuDataItem[] =>
  menus &&
  menus.map(({ icon, children, ...item }) => ({
    ...item,
    icon: icon && IconMap[icon as string],
    children: children && loopMenuItem(children),
  }));

const BasicLayout = (props: any) => {
  useEffect(() => {
    props.dispatch({ type: 'enoadRouter/fetchMenus' });
    props.dispatch({ type: 'enoadRouter/fetchLoginUser' });

    NoticeEmitter.addListener(ENOAD_ERROR, (data: any) => {
      message.error(data);
    });
    NoticeEmitter.addListener(ENOAD_LOGIN_OUT, (data: any) => {
      doLogin();
    });

  }, []);

  return (
    <>
      <ProLayout
        navTheme={'light'}
        fixSiderbar
        fixedHeader={true}
        menuDataRender={() => loopMenuItem(props.menus)}
        menuItemRender={(menuItemProps, defaultDom) =>
          menuItemProps.isUrl ? (
            defaultDom
          ) : (
            <Link className="qixian-menuItem" to={menuItemProps.path || '/'}>
              {defaultDom}
            </Link>
          )
        }
        onMenuHeaderClick={() => history.push('/')}
        menuHeaderRender={false}
        headerRender={() => <GlobalHeader {...props} />}
        {...props}
      >
        <div className={styled.layoutBody}>
          <div className={styled.childrenContainer}>{props.children}</div>
        </div>
      </ProLayout>
    </>
  );
};

export default connect(({ enoadRouter }) => ({
  ...enoadRouter,
}))(BasicLayout);
